<?php

namespace app\api\controller;

use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;
use think\Queue;
use think\Response;

/**
 * 大数据导出
 */
class ExportDemo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 分批导出
    public function batchExport()
    {
        // 设置内存
        ini_set('memory_limit', '512M');
        set_time_limit(0);

        // 初始化sheet
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $header = ['订单表id', '渠道类型', '渠道id', '店铺id', '订单号', '订单号流水', '订单状态', '订单总金额', '订单总的优惠金额', '履约服务费', '顾客实付金额', '店铺实收金额', '下单时间', '下单日期', '预计送达时间', '自提时间', '是否预约单', '收货人姓名', '收货人电话', '顾客电话', '收货人地址', '地址经度', '地址纬度', '订单类型', '订单备注', '是否拼团订单', '订单是否降级'];
        $sheet->fromArray($header, null, 'A1');
        $column = 2;
        // 设置 A 列为文本格式
        $sheet->getStyle('C')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
        $sheet->getStyle('E')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
        $sheet->getStyle('S')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);

        // 分配查询数据
        $limit = 10000;
        $offset = 0;
        while (true) {
            $data = Db::name('order')->limit($offset, $limit)->select();
            if (empty($data)) {
                break;
            }
            foreach ($data as $row) {
                $sheet->setCellValue('A' . $column, $row['id']);
                if ($row['type'] == 0) {
                    $row['type'] = '美团';
                } else if ($row['type'] == 1) {
                    $row['type'] = '饿了么';
                } else {
                    $row['type'] = '未知';
                }
                $sheet->setCellValue('B' . $column, $row['type']);
                $sheet->setCellValue('C' . $column, $row['channelshop_id']);
                $sheet->setCellValue('D' . $column, $row['shop_id']);
                $sheet->setCellValue('E' . $column, $row['order_sn']);
                $sheet->setCellValue('F' . $column, $row['order_day_sn']);
                if ($row['status'] == 1) {
                    $row['status'] = '待支付';
                } else if ($row['status'] == 2) {
                    $row['status'] = '待接单';
                } else if ($row['status'] == 4) {
                    $row['status'] = '进行中';
                } else if ($row['status'] == 8) {
                    $row['status'] = '已完成';
                } else if ($row['status'] == 9) {
                    $row['status'] = '已取消';
                } else if ($row['status'] == 10) {
                    $row['status'] = '已退单';
                } else {
                    $row['status'] = '未知';
                }
                $sheet->setCellValue('G' . $column, $row['status']);
                $sheet->setCellValue('H' . $column, $row['total_amount']);
                $sheet->setCellValue('I' . $column, $row['total_activity_amount']);
                $sheet->setCellValue('J' . $column, $row['fulfill_service_fee']);
                $sheet->setCellValue('K' . $column, $row['total_price']);
                $sheet->setCellValue('L' . $column, $row['income']);
                $sheet->setCellValue('M' . $column, $row['createtime']);
                $sheet->setCellValue('N' . $column, $row['order_date']);
                $sheet->setCellValue('O' . $column, $row['instant_order_deliver_time']);
                $sheet->setCellValue('P' . $column, $row['pick_up_time']);
                if ($row['book'] == 0) {
                    $row['book'] = '默认';
                } else if ($row['book'] == 1) {
                    $row['book'] = '预定订单';
                } else if ($row['book'] == 2) {
                    $row['book'] = '即时订单';
                } else {
                    $row['book'] = '未知';
                }
                $sheet->setCellValue('Q' . $column, $row['book']);
                $sheet->setCellValue('R' . $column, $row['recipient_name']);
                $sheet->setCellValue('S' . $column, $row['recipient_phone']);
                $sheet->setCellValue('T' . $column, $row['user_phone']);
                $sheet->setCellValue('U' . $column, $row['recipient_address']);
                $sheet->setCellValue('V' . $column, $row['recipient_lng']);
                $sheet->setCellValue('W' . $column, $row['recipient_lat']);
                if ($row['pick_type'] == 0) {
                    $row['pick_type'] = '配送订单';
                } else if ($row['pick_type'] == 1) {
                    $row['pick_type'] = '到店自取';
                } else {
                    $row['pick_type'] = '未知';
                }
                $sheet->setCellValue('X' . $column, $row['pick_type']);
                $sheet->setCellValue('Y' . $column, $row['remark']);
                $sheet->setCellValue('Z' . $column, $row['is_grounp_order'] == 1 ? '是' : '否');
                $sheet->setCellValue('AA' . $column, $row['down_graded'] == 1 ? '是' : '否');
                $column++;
            }

            $offset += $limit;
        }

        // 设置响应头并输出文件
        $fileName = date('Ymdh') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $fileName);
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
    }

    // csv格式
    public function exportCSV()
    {
        // 设置响应头
        $fileName = date('Ymdh').'.csv';
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment;filename=".$fileName);
        header("Cache-Control: max-age=0");

        // 打开输出流
        $fp = fopen('php://output','w');

        // 设置表头
        $header = ['订单表id', '渠道类型', '渠道id', '店铺id', '订单号', '订单号流水', '订单状态', '订单总金额', '订单总的优惠金额', '履约服务费', '顾客实付金额', '店铺实收金额', '下单时间', '下单日期', '预计送达时间', '自提时间', '是否预约单', '收货人姓名', '收货人电话', '顾客电话', '收货人地址', '地址经度', '地址纬度', '订单类型', '订单备注', '是否拼团订单', '订单是否降级'];
        fputcsv($fp,$header);

        // 分批查询数据
        $limit = 10000;
        $offset = 0;
        while (true) {
            $data = Db::name('order')->limit($offset, $limit)->select();
            if (empty($data)) {
                break;
            }
            foreach ($data as $row) {
                if ($row['type'] == 0) {
                    $row['type'] = '美团';
                } else if ($row['type'] == 1) {
                    $row['type'] = '饿了么';
                } else {
                    $row['type'] = '未知';
                }

                if ($row['status'] == 1) {
                    $row['status'] = '待支付';
                } else if ($row['status'] == 2) {
                    $row['status'] = '待接单';
                } else if ($row['status'] == 4) {
                    $row['status'] = '进行中';
                } else if ($row['status'] == 8) {
                    $row['status'] = '已完成';
                } else if ($row['status'] == 9) {
                    $row['status'] = '已取消';
                } else if ($row['status'] == 10) {
                    $row['status'] = '已退单';
                } else {
                    $row['status'] = '未知';
                }

                if ($row['book'] == 0) {
                    $row['book'] = '默认';
                } else if ($row['book'] == 1) {
                    $row['book'] = '预定订单';
                } else if ($row['book'] == 2) {
                    $row['book'] = '即时订单';
                } else {
                    $row['book'] = '未知';
                }

                if ($row['pick_type'] == 0) {
                    $row['pick_type'] = '配送订单';
                } else if ($row['pick_type'] == 1) {
                    $row['pick_type'] = '到店自取';
                } else {
                    $row['pick_type'] = '未知';
                }
                $row['is_grounp_order'] = $row['is_grounp_order'] == 1 ? '是' : '否';
                $row['down_graded'] = $row['down_graded'] == 1 ? '是' : '否';
                $row = [
                    $row['id'],
                    $row['type'],
                    $row['channelshop_id'],
                    $row['shop_id'],
                    $row['order_sn'],
                    $row['order_day_sn'],
                    $row['status'],
                    $row['total_amount'],
                    $row['total_activity_amount'],
                    $row['fulfill_service_fee'],
                    $row['total_price'],
                    $row['income'],
                    $row['createtime'],
                    $row['order_date'],
                    $row['instant_order_deliver_time'],
                    $row['pick_up_time'],
                    $row['book'],
                    $row['recipient_name'],
                    $row['recipient_phone'],
                    $row['user_phone'],
                    $row['recipient_address'],
                    $row['recipient_lng'],
                    $row['recipient_lat'],
                    $row['pick_type'],
                    $row['remark'],
                    $row['is_grounp_order'],
                    $row['down_graded'],
                ];
                fputcsv($fp,$row);
            }

            $offset += $limit;
        }
        fclose($fp);
    }

    // 队列导出
    public function queueExport()
    {
        $userId = 1;
        $taskId = uniqid();

        Db::name('export_tasks')->insert([
            'user_id' => $userId,
            'task_id' => $taskId,
            'status' => 'processing',
            'createtime' => time()
        ]);

        Queue::push('app\job\ExportJob',['user_id' => $userId,'task_id' => $taskId],'export_queue');
        $this->success('正在导出请稍后下载',['taks_id' => $taskId]);
    }

    // 下载导出文件
    public function download()
    {
        $taskId = $this->request->get('task_id');
        if(!$taskId){
            $this->error('task_id不能为空');
        }
        $task = Db::name('export_tasks')->where('task_id',$taskId)->find();
        if(!$task || $task['status'] != 'completed'){
            $this->error('文件未生成或任务失败');
        }
        $this->success('成功',['file_path' => $task['file_path']]);
    }
}
